﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.MTHControlLib;
using thinger.MTHHelper;
using thinger.MTHModels;

namespace thinger.MTHProject
{
    public partial class FrmParamSet : Form
    {
        public FrmParamSet(string devPath)
        {
            InitializeComponent();

            this.devPath = devPath;
            //加载ini文件
            Devload();
            //
            Timer timer = new Timer();

            timer.Tick += Timer_Tick;
            timer.Interval = 1000;

            timer.Start();

            this.FormClosing += (sender, e) => 
            { 
                timer.Stop();
            };
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            //温湿度限值
            LimitData(CommonMethods.Device);
            //更新警告
            AlarmData(CommonMethods.Device);



        }

        private void LimitData(Device device)
        {
            if (device.IsConnected)
            {

                foreach (var item in this.MainPanel.Controls.OfType<TextSet>())
                {
                    if (item.BindVarName != null && item.BindVarName.ToString().Length > 0)
                    {
                        if (device != null && device.DictionaryVarValue.ContainsKey(item.BindVarName) && device.DictionaryVarValue[item.BindVarName] != null)
                        {
                            item.CurrentValue = Convert.ToSingle(device.DictionaryVarValue[item.BindVarName]);
                        }
                    }
                    if (item.AlarmVarName != null && item.AlarmVarName.ToString().Length > 0) 
                    {
                        if (device != null && device.DictionaryVarValue.ContainsKey(item.AlarmVarName) && device.DictionaryVarValue[item.AlarmVarName] != null)
                        {
                            item.IsAlarm = device.DictionaryVarValue[item.AlarmVarName].ToString() == "1" ? true : false;
                        }
                    }

                    
                }

            }
        }
        //更新警告
        private void AlarmData(Device device) 
        {
            if (device.IsConnected)
            {

                foreach (var item in this.MainPanel.Controls.OfType<CheckBoxEx>())
                {
                    if (item.Tag.ToString() != null && item.Tag.ToString().Length > 0) 
                    {
                        item.Checked = device.DictionaryVarValue[item.Tag.ToString()].ToString() == "1" ? true : false;
                    }
                }

            }
        }

        private string devPath = string.Empty;

        private void btnGroupConfig_Click(object sender, EventArgs e)
        {
            new FrmGroupConfig().ShowDialog();
        }

        private void btnVarlable_Click(object sender, EventArgs e)
        {
            new FrmVarlableConfig().ShowDialog();
        }

        private void btnAddDev_Click(object sender, EventArgs e)
        {

            bool isPost = IniConfigHelper.WriteIniData("设备信息", "端口号", this.textPost.Text.Trim(), devPath);
            bool isIPAdress = IniConfigHelper.WriteIniData("设备信息", "IP地址", this.textIPAdress.Text.Trim(), devPath);

            if (isIPAdress && isPost)
            {
                DialogResult dialogResult = new FrmMsgBoxWithAck("设备写入成功", "设备写入成功").ShowDialog();

                if (dialogResult == DialogResult.OK)
                {
                    CommonMethods.Device = new Device()
                    {
                        IPAdress = this.textIPAdress.Text.Trim(),
                        Port = Convert.ToInt32(this.textPost.Text.Trim()),
                    };
                    //重新连接
                    CommonMethods.Device.IsConnected = false;
                }



            }
            else
            {
                new FrmMsgBoxWithOutAck("设备写入失败", "设备信息失败").Show();
            }
            
            

        }

        private void btnConcelDev_Click(object sender, EventArgs e)
        {
            Device device = CommonMethods.Device;

            if (device != null)
            {
                this.textIPAdress.Text = device.IPAdress;
                this.textPost.Text = device.Port.ToString();
            }
            else
            {
                //没有保存的数据，就是默认127.0.0.1和502
                this.textIPAdress.Text = "127.0.0.1";
                this.textPost.Text = "502";
            }
        }
        /// <summary>
        /// 开局加载ini文件
        /// </summary>
        private void Devload()
        {
            string devName = Path.GetDirectoryName(devPath);

            if (!Directory.Exists(devName))
            {
                Directory.CreateDirectory(devName);

            }
            try
            {
                string IPAdress = IniConfigHelper.ReadIniData("设备信息", "IP地址", "127.0.0.1", devPath);

                string Post = IniConfigHelper.ReadIniData("设备信息", "端口号", "502", devPath);

                this.textIPAdress.Text = IPAdress;

                this.textPost.Text = Post;

                CommonMethods.Device = new Device()
                {
                    IPAdress = IPAdress,
                    Port = Convert.ToInt32(Post),
                };
            }
            catch (Exception)
            {

                return;
            }
            

        }

        private void Common_DoubleClick(object sender, EventArgs e)
        {
            if (sender is TextSet textSet)
            {
                if (textSet.BindVarName != null && textSet.BindVarName.Length > 0) 
                {
                    DialogResult dialogResult = new FrmModify(textSet.Title, textSet.CurrentValue.ToString(), textSet.BindVarName).ShowDialog();
                    if (dialogResult != DialogResult.OK)
                    {
                        CommonMethods.AddLog(2, $"{textSet.Title}修改失败");
                    }
                }
                
            }
        }

        private void Common_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is CheckBoxEx check) 
            {
                if (check.Tag != null && check.Tag.ToString().Length > 0)
                {
                    bool result = CommonMethods.CommonWriteModbusTcp(check.Tag.ToString().Trim(), check.Checked ? "1" : "0");
                    if (!result)
                    {
                        check.CheckedChanged -= Common_CheckedChanged;
                        check.Checked = !check.Checked;
                    }
                }

            }
        }

        private void Check_CheckedChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }
}
